package mcu.market.set;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.dom4j.io.DOMReader;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.Document;




import org.xml.sax.SAXException;

public class XmlSet {
	private static XmlSet instance = new XmlSet();
    String resource = "DataConfig.xml";
    org.dom4j.Document document=null;
    private XmlSet() {
    	DocumentBuilder dBuilder;
		try {
			
			dBuilder = DocumentBuilderFactory.newInstance()
			        .newDocumentBuilder();
			Document doc = dBuilder.parse(XmlSet.class.getResource(resource).toString());
			
			DOMReader domReader = new DOMReader();  
			document = domReader.read(doc);      
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
    }
    public static XmlSet getInstance() {
        return instance;
    }
    /**
     * 根據dom4j原則,example:"/project/open"
     * @param setRule
     * @return values
     */
    public String getSetValue(String setRule){
    	return document.selectSingleNode(setRule).getStringValue();
    }
    public void SetValue(String setRule,String value){
    	document.selectSingleNode(setRule).setText(value);
    	OutputFormat format = OutputFormat.createPrettyPrint(); 
        format.setEncoding("UTF-8"); 
        XMLWriter writer;
		try {
			writer = new XMLWriter(new FileWriter(new File(XmlSet.class.getResource(resource).toURI())),format);
			writer.write(document); 
	        writer.close(); 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
    }

}
